package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketComment;
import com.cskaoyan.market.db.domain.MarketGoods;
import com.cskaoyan.market.service.AdminCommentService;
import com.cskaoyan.market.service.AdminCommentServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/comment/*")
public class AdminCommentController extends HttpServlet {
    AdminCommentService adminCommentService=new AdminCommentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace("/admin/comment/", "");
        if ("list".equals(replace)){
            list(req,resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String userId = req.getParameter("userId");
        String valueId = req.getParameter("valueId");
        List<MarketComment> marketComments=adminCommentService.list(page,limit,sort,order,userId,valueId);

        Object o = ResponseUtil.okList(marketComments);
        String s = JacksonUtil.getObjectMapper().writeValueAsString(o);
        resp.getWriter().println(s);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace("/admin/comment/", "");
        if ("delete".equals(replace)){
            delete(req,resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s = req.getReader().readLine();
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketComment marketComment = objectMapper.readValue(s, MarketComment.class);
        if (adminCommentService.delete(marketComment.getId())!=0){
            Object ok = ResponseUtil.ok();
            String s1 = JacksonUtil.writeValueAsString(ok);
            resp.getWriter().println(s1);
            return;
        }
        Object fail = ResponseUtil.fail();
        String f = JacksonUtil.writeValueAsString(fail);
        resp.getWriter().println(f);
    }
}
